/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import HuffmanTableWriterWorkspace from './HuffmanTableWriterWorkspace'
import HuffmanCompressionTableWorkspace from './HuffmanCompressionTableWorkspace'
import HuffmanCompressionTable from './HuffmanCompressionTable'
import Huffman from './Huffman'

export default class HuffmanCompressionContext {
    private tableWriterWorkspace: HuffmanTableWriterWorkspace = new HuffmanTableWriterWorkspace();
    private compressionTableWorkspace: HuffmanCompressionTableWorkspace = new HuffmanCompressionTableWorkspace();
    private previousTable: HuffmanCompressionTable = new HuffmanCompressionTable(Huffman.MAX_SYMBOL_COUNT);
    private temporaryTable: HuffmanCompressionTable = new HuffmanCompressionTable(Huffman.MAX_SYMBOL_COUNT);
    private previousCandidate: HuffmanCompressionTable = this.previousTable;
    private temporaryCandidate: HuffmanCompressionTable = this.temporaryTable;

    public getPreviousTable(): HuffmanCompressionTable
    {
        return this.previousTable;
    }

    public borrowTemporaryTable(): HuffmanCompressionTable
    {
        this.previousCandidate = this.temporaryTable;
        this.temporaryCandidate = this.previousTable;

        return this.temporaryTable;
    }

    public discardTemporaryTable(): void
    {
        this.previousCandidate = this.previousTable;
        this.temporaryCandidate = this.temporaryTable;
    }

    public saveChanges(): void
    {
        this.temporaryTable = this.temporaryCandidate;
        this.previousTable = this.previousCandidate;
    }

    public getCompressionTableWorkspace(): HuffmanCompressionTableWorkspace
    {
        return this.compressionTableWorkspace;
    }

    public getTableWriterWorkspace(): HuffmanTableWriterWorkspace
    {
        return this.tableWriterWorkspace;
    }
}
